package com.bcu.cn.onlineexamsystem.studentmanage.controller;

import com.bcu.cn.onlineexamsystem.studentmanage.service.ScoreAnalysisService;
import com.bcu.cn.onlineexamsystem.user.entity.User;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import org.springframework.http.MediaType;
import reactor.core.publisher.Flux;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 成绩分析控制器
 */
@Controller
@RequestMapping("/student/score")
public class ScoreAnalysisController {
    
    private static final Logger logger = LoggerFactory.getLogger(ScoreAnalysisController.class);
    
    @Autowired
    private ScoreAnalysisService scoreAnalysisService;
    
    @Autowired
    private com.bcu.cn.onlineexamsystem.studentmanage.service.DeepSeekService deepSeekService;
    
    /**
     * 获取当前登录的学生ID
     */
    private String getCurrentStudentId(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            logger.error("用户未登录");
            throw new RuntimeException("用户未登录");
        }
        if (!"student".equals(user.getRole())) {
            logger.error("非学生用户，无权访问");
            throw new RuntimeException("非学生用户，无权访问");
        }
        return user.getUserId();
    }
    
    /**
     * 成绩分析主页面
     */
    @GetMapping("/analysis")
    public String scoreAnalysisPage(HttpSession session, Model model) {
        logger.info("=== 成绩分析页面访问开始 ===");
        
        try {
            String studentId = getCurrentStudentId(session);
            logger.info("学生ID: {}", studentId);
            
            // 获取基础统计数据
            var statistics = scoreAnalysisService.getScoreStatistics(studentId);
            logger.info("获取统计数据成功: {}", statistics);
            model.addAttribute("statistics", statistics);
            
            logger.info("=== 成绩分析页面访问结束 ===");
            return "student/score/analysis";
        } catch (Exception e) {
            logger.error("获取统计数据失败", e);
            model.addAttribute("error", "获取统计数据失败: " + e.getMessage());
            return "student/score/analysis";
        }
    }
    
    /**
     * 获取成绩统计数据API
     */
    @GetMapping("/api/statistics")
    @ResponseBody
    public Map<String, Object> getStatistics(HttpSession session) {
        logger.info("=== API调用: 获取统计数据 ===");
        
        Map<String, Object> result = new HashMap<>();
        try {
            String studentId = getCurrentStudentId(session);
            logger.info("学生ID: {}", studentId);
            
            var statistics = scoreAnalysisService.getScoreStatistics(studentId);
            logger.info("统计数据获取成功: {}", statistics);
            
            result.put("success", true);
            result.put("data", statistics);
            logger.info("API返回结果: {}", result);
        } catch (Exception e) {
            logger.error("获取统计数据失败", e);
            result.put("success", false);
            result.put("message", "获取统计数据失败：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 获取成绩趋势数据API
     */
    @GetMapping("/api/trend")
    @ResponseBody
    public Map<String, Object> getScoreTrend(HttpSession session) {
        logger.info("=== API调用: 获取趋势数据 ===");
        
        Map<String, Object> result = new HashMap<>();
        try {
            String studentId = getCurrentStudentId(session);
            logger.info("学生ID: {}", studentId);
            
            var trendData = scoreAnalysisService.getScoreTrend(studentId);
            logger.info("趋势数据获取成功: {}", trendData);
            
            result.put("success", true);
            result.put("data", trendData);
            logger.info("API返回结果: {}", result);
        } catch (Exception e) {
            logger.error("获取趋势数据失败", e);
            result.put("success", false);
            result.put("message", "获取趋势数据失败：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 获取成绩分布数据API
     */
    @GetMapping("/api/distribution")
    @ResponseBody
    public Map<String, Object> getScoreDistribution(HttpSession session) {
        logger.info("=== API调用: 获取分布数据 ===");
        
        Map<String, Object> result = new HashMap<>();
        try {
            String studentId = getCurrentStudentId(session);
            logger.info("学生ID: {}", studentId);
            
            var distributionData = scoreAnalysisService.getScoreDistribution(studentId);
            logger.info("分布数据获取成功: {}", distributionData);
            
            result.put("success", true);
            result.put("data", distributionData);
            logger.info("API返回结果: {}", result);
        } catch (Exception e) {
            logger.error("获取分布数据失败", e);
            result.put("success", false);
            result.put("message", "获取分布数据失败：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 获取课程成绩分析API
     */
    @GetMapping("/api/course-analysis")
    @ResponseBody
    public Map<String, Object> getCourseAnalysis(HttpSession session) {
        logger.info("=== API调用: 获取课程分析 ===");
        
        Map<String, Object> result = new HashMap<>();
        try {
            String studentId = getCurrentStudentId(session);
            logger.info("学生ID: {}", studentId);
            
            var courseData = scoreAnalysisService.getCourseScoreAnalysis(studentId);
            logger.info("课程分析数据获取成功: {}", courseData);
            
            result.put("success", true);
            result.put("data", courseData);
            logger.info("API返回结果: {}", result);
        } catch (Exception e) {
            logger.error("获取课程分析失败", e);
            result.put("success", false);
            result.put("message", "获取课程分析失败：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 获取最近考试记录API
     */
    @GetMapping("/api/recent-records")
    @ResponseBody
    public Map<String, Object> getRecentRecords(@RequestParam(defaultValue = "5") Integer limit, HttpSession session) {
        logger.info("=== API调用: 获取最近记录 ===");
        
        Map<String, Object> result = new HashMap<>();
        try {
            String studentId = getCurrentStudentId(session);
            logger.info("学生ID: {}, 限制数量: {}", studentId, limit);
            
            var records = scoreAnalysisService.getRecentExamRecords(studentId, limit);
            logger.info("最近记录获取成功: {}", records);
            
            result.put("success", true);
            result.put("data", records);
            logger.info("API返回结果: {}", result);
        } catch (Exception e) {
            logger.error("获取最近记录失败", e);
            result.put("success", false);
            result.put("message", "获取最近记录失败：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 获取考试详情API
     */
    @GetMapping("/api/exam-detail/{examId}")
    @ResponseBody
    public Map<String, Object> getExamDetail(@PathVariable Long examId, HttpSession session) {
        logger.info("=== API调用: 获取考试详情 ===");
        
        Map<String, Object> result = new HashMap<>();
        try {
            String studentId = getCurrentStudentId(session);
            logger.info("学生ID: {}, 考试ID: {}", studentId, examId);
            
            var examDetail = scoreAnalysisService.getExamScoreDetail(studentId, examId);
            logger.info("考试详情获取成功: {}", examDetail);
            
            result.put("success", true);
            result.put("data", examDetail);
            logger.info("API返回结果: {}", result);
        } catch (Exception e) {
            logger.error("获取考试详情失败", e);
            result.put("success", false);
            result.put("message", "获取考试详情失败：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 成绩详情页面
     */
    @GetMapping("/detail/{examId}")
    public String examDetailPage(@PathVariable Long examId, HttpSession session, Model model) {
        logger.info("=== 考试详情页面访问 ===");
        
        try {
            String studentId = getCurrentStudentId(session);
            logger.info("学生ID: {}, 考试ID: {}", studentId, examId);
            
            Map<String, Object> examDetail = scoreAnalysisService.getExamScoreDetail(studentId, examId);
            logger.info("考试详情获取成功: {}", examDetail);
            model.addAttribute("examDetail", examDetail);
        } catch (Exception e) {
            logger.error("获取考试详情失败", e);
            model.addAttribute("error", "获取考试详情失败: " + e.getMessage());
        }
        
        return "student/score/detail";
    }
    
    /**
     * 课程成绩页面
     */
    @GetMapping("/course")
    public String courseScorePage(HttpSession session, Model model) {
        logger.info("=== 课程成绩页面访问 ===");
        
        try {
            String studentId = getCurrentStudentId(session);
            logger.info("学生ID: {}", studentId);
            
            var courseAnalysis = scoreAnalysisService.getCourseScoreAnalysis(studentId);
            logger.info("课程分析数据获取成功: {}", courseAnalysis);
            model.addAttribute("courseAnalysis", courseAnalysis);
        } catch (Exception e) {
            logger.error("获取课程分析失败", e);
            model.addAttribute("error", "获取课程分析失败: " + e.getMessage());
        }
        
        return "student/score/course";
    }
    

    /**
     * 数据库检查接口
     */
    @GetMapping("/api/db-check")
    @ResponseBody
    public Map<String, Object> checkDatabase(HttpSession session) {
        logger.info("=== 数据库检查接口调用 ===");
        
        Map<String, Object> result = new HashMap<>();
        try {
            String studentId = getCurrentStudentId(session);
            
            // 检查学生是否存在
            List<Map<String, Object>> studentRecords = scoreAnalysisService.getRecentExamRecords(studentId, 1);
            logger.info("学生记录检查: {}", studentRecords);
            
            // 检查统计数据
            var stats = scoreAnalysisService.getScoreStatistics(studentId);
            logger.info("统计数据检查: {}", stats);
            
            result.put("success", true);
            result.put("studentExists", !studentRecords.isEmpty());
            result.put("studentRecords", studentRecords);
            result.put("statistics", stats);
            
        } catch (Exception e) {
            logger.error("数据库检查失败", e);
            result.put("success", false);
            result.put("error", e.getMessage());
        }
        
        return result;
    }

    /**
     * AI智能对话接口
     */
    @PostMapping("/api/ai-chat")
    @ResponseBody
    public Map<String, Object> aiChat(@RequestBody Map<String, String> req, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            String studentId = getCurrentStudentId(session);
            String question = req.get("question");
            String answer = scoreAnalysisService.askAI(studentId, question);
            result.put("success", true);
            result.put("data", answer);
        } catch (Exception e) {
            result.put("success", false);
            result.put("data", "AI服务暂时不可用");
        }
        return result;
    }

    /**
     * AI自动学习建议接口
     */
    @PostMapping("/api/ai-suggestion")
    @ResponseBody
    public Map<String, Object> aiSuggestion(HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            String studentId = getCurrentStudentId(session);
            String answer = scoreAnalysisService.askAISuggestion(studentId);
            result.put("success", true);
            result.put("data", answer);
        } catch (Exception e) {
            result.put("success", false);
            result.put("data", "AI服务暂时不可用");
        }
        return result;
    }

    /**
     * AI智能对话流式接口
     */
    @PostMapping(value = "/api/ai-chat-stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @ResponseBody
    public SseEmitter aiChatStream(@RequestBody Map<String, String> req, HttpSession session) {
        SseEmitter emitter = new SseEmitter(180000L);
        String studentId = getCurrentStudentId(session);
        String question = req.get("question");
        Flux<String> flux = deepSeekService.callDeepSeekStream(studentId, question);
        flux.subscribe(
            content -> {
                try { emitter.send(content); } catch (Exception e) { emitter.completeWithError(e); }
            },
            error -> emitter.completeWithError(error),
            emitter::complete
        );
        return emitter;
    }
} 